# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import hashlib
import datetime

from sqlalchemy.orm import *
#from dao.User import User
from dao.Access import Access
from web_lib.webutils import *
from lib.utils import prep2json
#from Environment import schema
from web_lib.session import Session
from web_lib.page import Page

@expose('/prelogin')
def prelogin(req=None, SUB=""):
    pageData = {'file': 'pg/login',}
    return Page(req).render(pageData)

@expose('/italiaCives/login_ic')
def login_ic(req=None):
    """
    Gestione procedura di login
    """
    from dao.Operatore import Operatore
    username = req.form.get('username')
    if username:
        username = username.strip().lower()
    passwordd = req.form.get('password')
    if not username or not req.cookies:
        host_url = "/italiaCives/dashboard"
        return Page(req).redirect(host_url)
    rows = Operatore().select(username=str(username),
                    password=hashlib.md5(username+passwordd).hexdigest())
    if len(rows) == 1:
        md5_passwd = hashlib.md5(username+passwordd).hexdigest()
        id_oper = rows[0].id
        item = prep2json(rows[0])
        jasoned = json.dumps(item,sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False, encoding='utf8')
        salvaInSessione(req, sezione="Main", chiave="id_oper", valore=id_oper)
        salvaInSessione(req, sezione="Main", chiave="username", valore=username)
        salvaInSessione(req, sezione="Main", chiave="md5_passwd", valore=md5_passwd)
        salvaInSessione(req, sezione="Main", chiave="json_oper", valore=jasoned)

        item = {"result":"OK",
                "msg":"Login su ItaliaCives Effettuato",
                }
    else:
        a =  Operatore().select(username=str(username))
        if a:
            item = {"result":"ERROR",
                "msg":"Password errata"
                }
        else:
            item = {"result":"ERROR",
                    "msg":"Username e Password errati"
                }
    jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
    return Response(jasoned)

@expose('/italiaCives/logout')
def logout_ic(req, SUB =""):
    """
    Gestione procedura di logout
    """
    salvaInSessione(req, sezione="Main", chiave="id_oper", valore=None)
    salvaInSessione(req, sezione="Main", chiave="schema", valore=None)
    #id_user = Session(req).getUserId()
    #Session(req).destroy()
    #datelogout = datetime.datetime.now()
    #access = Access(req=req)
    #access.id_user = id_user
    #access.logout = datelogout
    #access.persist()
    host_url= "/italiaCives"
    return Page(req).redirect(host_url)

@expose('/italiaCives/insertinthisente')
def insertinthisente_ic(req):
    print " DEVO SALVARE OPER QUI"
    oper = json.loads(leggiInSessione(req, sezione="Main", chiave="json_oper"))
    if oper and oper != "":
        from dao.Operatore import Operatore
        o = Operatore()
        o.username = oper["username"]
        o.password = oper["password"]
        o.email = oper["email"]
        o.cognome = oper["cognome"]
        o.nome =  oper["nome"]
        o.registration_date = datetime.datetime.now()
        o.last_modified = datetime.datetime.now()
        o.photo = oper["photo"]
        o.icona = oper["icona"]
        o.cellulare = oper["cellulare"]
        o.f_qrcode = oper["f_qrcode"]
        o.f_ean = oper["f_ean"]
        o.f_imei = oper["f_imei"]
        o.f_idreg = oper["f_idreg"]
        #o.data_nascita = oper["data_nascita"]
        o.active = False
        o.tipo_operatore =  oper["tipo_operatore"]
        o.genere =   oper["genere"]
        o.privacy =  oper["privacy"]
        o.mailing_list =  oper["mailing_list"]

        o.persist()
        salvaInSessione(req, sezione="Main", chiave="id_oper", valore=o.id)
    host_url= "/italiaCives"
    return Page(req).redirect(host_url)
